package cool.mtc.minio;

import io.minio.*;

/**
 * @author 明河
 */
public class MinioTemplate {
    private final MinioProperties minioProperties;

    public MinioTemplate(MinioProperties minioProperties) {
        this.minioProperties = minioProperties;
    }

    public void upload(String bucketName, String fileName, String filePath) throws Exception {
        MinioClient client = this.getMinioClient();
        this.ensureBucketExist(bucketName);
        UploadObjectArgs args = UploadObjectArgs.builder().bucket(bucketName).object(fileName).filename(filePath).build();
        client.uploadObject(args);
    }

    public void download(String bucketName, String fileName, String filePath) throws Exception {
        MinioClient client = this.getMinioClient();
        DownloadObjectArgs args = DownloadObjectArgs.builder().bucket(bucketName).object(fileName).filename(filePath).overwrite(true).build();
        client.downloadObject(args);
    }

    public void ensureBucketExist(String bucketName) throws Exception {
        MinioClient client = this.getMinioClient();
        boolean exist = client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (exist) {
            return;
        }
        client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());

    }

    public MinioClient getMinioClient() {
        return MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();
    }
}
